/*********************************************************************************
 *      Copyright:  (C) 2022 YanlinZhou<1222>
 *                  All rights reserved.
 *
 *       Filename:  getopt.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/09/2022)
 *         Author:  YanlinZhou <1222>
 *      ChangeLog:  1, Release initial version on "04/09/2022 10:48:11 AM"
 *                 
 ********************************************************************************/

#include "socket.h"

int  print_client_usage(char *progname)
{
    printf("\t******************* %s usage ********************\n", progname);
	printf("\t\t@ %s usage: \n", progname);
	printf("\t\t@ -i(--ipaddr): sepcify server IP address\n");
	printf("\t\t@ -p(--port): seypcify server port.\n");
	printf("\t\t@ -t(--time): specify sampling interval\n");
	printf("\t\t@ -d(--deamon): running in the background\n");
	printf("\t\t@ -h(--help): printf this help information.\n");
    printf ("\t ******************* end *************************\n");
	return 1;
}

int socket_client_init(socket_info_t *sokt)
{
		sokt->connect_fd = 0;
        int                     rv = -1;
        struct sockaddr_in      serv_addr;
        char                    buf[1024];

        sokt->connect_fd = socket(AF_INET, SOCK_STREAM, 0);
        if( sokt->connect_fd < 0)
        {
                printf("Creat connect_fd failure:%s\n",strerror(errno));
                return -1;
        }

        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(sokt->server_port);
        inet_aton(sokt->server_ip, &serv_addr.sin_addr);

        if( (rv = connect(sokt->connect_fd, (const struct sockaddr *) (&serv_addr), sizeof(serv_addr))) < 0)
        {
 //               printf("Connect to server[%s:%d]failure:%s\n",sokt->server_ip, sokt->server_port, strerror(errno));
				close(sokt->connect_fd);
				sokt->connect_fd = -1;
                return -2;
        }
		else
		{
			return sokt->connect_fd;
		}
}

int send_table_first_roll(socket_info_t *sokt, char *str)
{
    int rv = -1;
    if( (rv = write(sokt->connect_fd, str, 64)) < 0 )
    {
//      printf("write failure :%s", strerror(errno));
        close(sokt->connect_fd);
        sokt->connect_fd = -1;
        return -1;
    }
//	printf ("write[%d] Bytes to server sucessfully!\n", rv);
    return 1;
}

int send_sample_data(socket_info_t *sokt, char *sample_data)
{
    int rv = -1; 
    rv = write(sokt->connect_fd, sample_data, 64);
//	printf ("write[%d] Bytes sample data to server sucessfully!\n", rv);

    /* send failure */
    if( rv<0 )
    {   
        sokt->connect_fd = -1; 
        close(sokt->connect_fd);
        return -1; 
    }   

    /* send sucessfully */
    else
    {   
        return 0;
    }   
}

